package com.yidu.boss.config;



import com.yidu.boss.sys.domain.User;
import com.yidu.boss.sys.domain.UserExample;

import com.yidu.boss.sys.service.impl.UserServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author luoyushan
 */
public class UserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //创建执行对象
        SimpleAuthorizationInfo Info = new SimpleAuthorizationInfo();
        //获取当前的用户
        User primaryUser = (User) principalCollection.getPrimaryPrincipal();
        //获取当前用户角色和权限并分割成数组
        String[] split = primaryUser.getRole().split(",");
        String[] split1 = primaryUser.getPermission().split(",");
        //角色数组转化为list集合
        List<String> roles = Arrays.asList(split);
        List<String> permission=Arrays.asList(split1);
        //为当前主体授权
        Info.addRoles(roles);
        for (String s : permission) {
            Info.addStringPermission(s);
        }

        //返回执行对象
        return Info;
    }

    @Autowired
    UserServiceImpl userService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //创建用户令牌对象
        UsernamePasswordToken userToken=(UsernamePasswordToken) authenticationToken;
        //根据条件查询用户
        User user = userService.doLogin(userToken.getUsername());
        //遍历用户对象 并将结果赋值给user
        //判断user是否存在 返回null并会抛出异常
        if (user==null) {
            return null;
        }

        //返回数据 将用户名和密码传入
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
